﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace ProjetS5
{
    public class Map
    {
        public String Name;
        public Texture2D MapTexture;
        public Tile[][] Tiles;
        public int TileSize;
        public Rectangle MapRectangle;
        public float ratio = 1;

        public Map(string Name, Texture2D T,float ratio)
        {
            this.ratio = ratio;
            this.Name = Name;
            MapTexture = T;
            MapRectangle = new Rectangle(0, 0, (int)(MapTexture.Bounds.Width*this.ratio), (int)(MapTexture.Bounds.Height*this.ratio));
            TileSize = 8;
            ConstructionTiles();
            Load(Name + ".map");
        }

        public void Save(string file)
        {
            FileStream f;
            if (!File.Exists(file))
                f = File.Create(file);
            else
            {
                f = File.OpenWrite(file);
                f.SetLength(0);
            }

            List<byte> data = new List<byte>();

            for (int i = 0; i < Tiles.Length; i++)
                for (int j = 0; j < Tiles[i].Length; j++)
                    data.AddRange(BitConverter.GetBytes(Tiles[i][j].isCrossable));

            f.Write(data.ToArray(), 0, data.Count);
            f.Close();
        }

        public void Load(string file)
        {
            FileStream f;
            if (File.Exists(file))
            {
                f = File.OpenRead(file);
                Queue<bool> data = new Queue<bool>(); ;
                int eof = 0;
                do
                {
                    byte[] b = new byte[sizeof(bool)];
                    eof = f.Read(b, 0, sizeof(bool));
                    if (eof != 0)
                        data.Enqueue(BitConverter.ToBoolean(b, 0));
                }
                while (eof != 0);

                for (int i = 0; i < Tiles.Length; i++)
                    for (int j = 0; j < Tiles[i].Length; j++)
                        Tiles[i][j].isCrossable = data.Dequeue();
            }
        }

        public void ConstructionTiles()
        {
            if (MapTexture == null)
                return;

            Tiles = new Tile[MapTexture.Bounds.Width / TileSize + MapTexture.Bounds.Width % TileSize][];

            for (int i = 0; i < Tiles.Length; i++)
            {
                Tiles[i] = new Tile[MapTexture.Bounds.Height / TileSize + MapTexture.Bounds.Height % TileSize];
                for (int j = 0; j < Tiles[i].Length; j++)
                    Tiles[i][j] = new Tile();
            }
        }
    }
}